<template>
  <n-space :wrap="false">
    <n-card class="add-category" title="管理分类">
      <n-form
        ref="formRef"
        inline
        :model="formValue"
        label-placement="left"
        :rules="rules"
      >
        <n-form-item label="分类名" path="name">
          <n-input v-model:value="formValue.name" />
        </n-form-item>
        <n-form-item>
          <n-button @click="addCategory"> 保存 </n-button>
        </n-form-item>
      </n-form>
    </n-card>
    <n-card class="add-category" title="所有分类">
      <n-space>
        <template v-for="(item, index) in categoryList" :key="index">
          <n-button
            icon-placement="right"
            @click="delCategory(item.id)"
            secondary
            strong
          >
            <template #icon>
              <n-icon>
                <Close />
              </n-icon>
            </template>
            {{ item.name }}
          </n-button>
        </template>
      </n-space>
    </n-card>
  </n-space>
</template>

<script setup lang="ts">
import {
  NSpace,
  NForm,
  NFormItem,
  NInput,
  NButton,
  NCard,
  NIcon,
  type FormInst,
} from "naive-ui";
import { Close } from "@vicons/ionicons5";
import {
  create as apiCategoryCreate,
  findAll as apiFindAllCategories,
  type CategoryShow,
} from "~/api/category";
useHead({
  title: "分类列表", //网站标题
});
definePageMeta({
  title: "文章管理-分类列表",
});
const rules = {
  name: {
    pattern: /^.{0,10}$/,
    message: "长度小于10",
    required: true,
    trigger: "input",
  },
};
const formValue = ref({
  name: "",
});
const formRef = ref<FormInst | null>(null);
const addCategory = (e: MouseEvent) => {
  e.preventDefault();
  formRef.value?.validate(async (errors) => {
    if (!errors) {
      const { name } = formValue.value;
      const res = await apiCategoryCreate({ name });
      if (res.code === 0) {
        getcategories();
      }
    } else {
      naiveui.message.error(errors[0][0].message ?? "表单验证错误");
    }
  });
};
const delCategory = (id: number) => {
  console.log(id);
};
const categoryList = ref<CategoryShow[]>();
const getcategories = async () => {
  const res = await apiFindAllCategories();
  categoryList.value = res.data;
};
onMounted(() => {
  getcategories();
});
</script>
<style lang="scss" scoped>
.add-category {
  
  padding: 20px 15px;
}
</style>
